from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.common.by import By

from locators.sign_in import AuthenticationLocators
from pages.base import BasePage
from locators import AuthorizationLocators, AccountListLocators
import pages


class AuthenticationPage(BasePage):
    URl_BY_BACK_BT = "https://passport.yandex.ru/auth/add"
    URL = "https://passport.yandex.ru/auth"

    def __init__(self, driver: WebDriver):
        super().__init__(driver)

    def input_login(self, login: str):
        if self.check_element(AuthorizationLocators.TOGGLE):
            self._switch_to_legacy_toggle()

        login_field = self.find_element(AuthorizationLocators.LOGIN)
        login_field.send_keys(login)
        submit_bt = self.find_element(AuthorizationLocators.SUBMIT)
        submit_bt.submit()

        self.wait_new_page(AuthorizationPage.URL)

        return AuthorizationPage(self.driver)

    def _switch_to_legacy_toggle(self):
        buttons = self.find_element(AuthorizationLocators.TOGGLE)
        buttons.click()

    def get_error_text(self):
        error_text = self.get_element_text(AuthorizationLocators.ERROR)
        return error_text


class AuthorizationPage(BasePage):
    URL = "https://passport.yandex.ru/auth/welcome"

    def __init__(self, driver: WebDriver):
        super().__init__(driver)

    def input_password(self, passwd: str):
        password_field = self.find_element(AuthenticationLocators.PASSWORD)
        password_field.send_keys(passwd)
        submit_bt = self.find_element(AuthenticationLocators.SUBMIT)
        submit_bt.submit()
        self.wait_new_page("https://passport.yandex.ru/profile")

        return pages.ProfilePage(self.driver)

    def back_by_user_bt_click(self):
        found_user = self.find_element(AuthenticationLocators.CHOSEN_USER)
        found_user.click()

        self.wait_new_page(AuthenticationPage.URl_BY_BACK_BT)
        return AuthenticationPage(self.driver)

    def get_error_text(self):
        error_text = self.get_element_text(AuthenticationLocators.ERROR)
        return error_text


class AccountListPage(BasePage):
    URL = "https://passport.yandex.ru/auth/list"

    def __init__(self, driver: WebDriver):
        super().__init__(driver)

    def logout(self):
        self._open_context_menu()
        logout_bt = self.find_element(AccountListLocators.LOGOUT_BT_LOCATOR)
        logout_bt.click()

        self.wait_new_page(AuthorizationPage.URL)
        return AuthenticationPage(self.driver)

    def logout_with_list_flushing(self):
        self._open_context_menu()
        logout_bt = self.find_element(AccountListLocators.LOGOUT_WITH_FLUSH_BT_LOCATOR)
        logout_bt.click()

        self.wait_new_page(AuthenticationPage.URl_BY_BACK_BT)
        return AuthorizationPage(self.driver)

    def _open_context_menu(self):
        context_bt = self.find_element(AccountListLocators.CONTEXT_BT_LOCATOR)
        context_bt.click()
